package com.maltys.config.security;

import com.maltys.config.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@Profile("jwt")
public class JwtSecurityConfig extends BaseSecurityConfig {
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Bean
    public SecurityFilterChain securityFilterChainForJwt(HttpSecurity httpSecurity) throws Exception {
        // 放行option请求
        httpSecurity.authorizeRequests().antMatchers(HttpMethod.OPTIONS).permitAll()
                // 关闭跨域防护
                .and().csrf().disable();

        // 关闭session
        httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        return httpSecurity
                .authorizeRequests()
                // 放行的请求
                .antMatchers("/user/registry","/user/login").permitAll()
                .anyRequest().authenticated()
                // jwt token登录
                .and().addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
                .build();
    }
}
